import { formatNumber, messages, setLocalStorageWithAutoStringify } from "share/common";
import ReportCommonUtils from "components/template/graphic-report/report-common-utils";
import React from "react";
import {Tooltip} from "antd";

export const COLOR_LIST = [
  '#4A7DCD',
  '#FFC67B',
  '#FF7F00',
  '#52C793'
];

const BAR_COLOR_LIST = [
  '#5BA4FF',
  '#FF956D',
  '#49C7BA',
  '#4A8DFF'
];

const PIE_COLOR_LIST = [
  '#5CA0F2',
  '#FFB157',
  '#72CDA4',
  '#6BDBFC',
  '#FFD54C',
  '#8E99B2'
];

export function toggleShowLabel({ config, options }) {
  const { showLabel } = config;
  if (options && options.series) {
    options.series.forEach(item => {
      if (item.label) {
        item.label.normal.show = showLabel;
      }
    })
  }
  return Object.assign({}, options)
}

export function popoverTitle(columns) {
  columns.forEach(column => {
    column.title = <Tooltip placement="top" title={column.title}>{column.title}</Tooltip>
    return column
  })
  return columns
}

export function commonUtilsFactory(options) {

  const {
    context,
    config,
    reportType,
    reportKeyPrefix,
    allowSetting = true,
    allowExport = false,
  } = options;

  let props = {
    allowSetting,
    allowExport
  };

  if (allowSetting) {
    let { showLabel } = config;
    const settingChildren = [{
      id: 'showLabel',
      label: messages('finance-7.key153')/*展示数值*/,
      value: showLabel
    }];

    const onSettingChange = (id, value) => {
      if (id === 'showLabel') {
        const { reportConfig } = context.state;
        reportConfig[reportType].showLabel = value;
        setLocalStorageWithAutoStringify(reportKeyPrefix + reportType, value);
        context.setState({
          reportConfig
        })
      }
    };
    props.settingChildren = settingChildren;
    props.onSettingChange = onSettingChange;
  }

  if (allowExport) {
    const propsArray = ['reportCode', 'exportDisable', 'exportParams', 'exportType', 'exportUrl'];

    propsArray.forEach(key => {
      props[key] = options[key];
    });
  }

  return (
    <ReportCommonUtils
      {...props}
    />
  );
}

/**
 * 通用饼图模板生成方法
 * @params verticalLegend legend是否垂直排列
 * @returns {{tooltip: {trigger: string, formatter: (function(*): string)}, legend: {bottom: number, left: string, data: Array}, series: {type: string, radius: string[], data: Array}[]}}
 */
export function pieTemplateFactory(verticalLegend) {

  let legend = verticalLegend ? {
    orient: 'vertical',
    top: 'center',
    left: 20,
    itemGap: 20,
    data: []
  } : {
    bottom: 10,
    left: 'center',
    data: []
  };
  return {
    tooltip: {
      trigger: 'item',
      formatter: (item) => lengthStrShow(item.name) + ":</br>" + formatNumber(item.value) + "</br>" + item.data._percentageStr
    },
    legend,
    series: [
      {
        type: 'pie',
        radius: ['45%', '60%'],
        center: ['60%', '50%'],
        data: [],
        label: {
          normal: {
            show: true,
            position: 'right'
          }
        },
      }
    ],
    color: PIE_COLOR_LIST
  }
}

/**
 * 通用柱状图模板生成方法
 * @params colorIndex 使用第几种颜色
 */
export function barTemplateFactory(colorIndex = 0, showLegend) {
  colorIndex %= 4;
  return {
    legend: {
      show: showLegend,
      bottom: 10,
      left: 'center',
      data: []
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params = []) => {
        let item = params[0] || {};
        let { data, value } = item;
        data = data || {};
        let { label, _percentageStr } = data;
        return `${lengthStrShow(label)}:<br>${formatNumber(value)}<br>${_percentageStr}`
      }
    },
    axisLabel: {
      interval: 119, // 自定义显示X轴坐标显示间隔
      textStyle: {
        fontSize: '10',
      },
    },
    grid: {
      y: 20,
      left: '3%',
      right: '4%',
      bottom: showLegend ? '50' : '3%',
      containLabel: true
    },
    yAxis: [
      {
        data: [],
        inverse: true,
        axisLine: {
          lineStyle: {
            color: '#DBE6F3'
          }
        },
        axisTick: {
          show: false
        },
      }
    ],
    xAxis: [
      {
        type: 'value',
        boundaryGap: ['0', '15%'],  // 右侧留白用于显示label
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#EBF0F5'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#DBE6F3'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          interval: 0,
          rotate: 45,
          margin: 10,
          color: '#B5C0CE',
          fontSize: 12
        },
      }
    ],
    series: [
      {
        type: 'bar',
        barWidth: 10,
        data: [],
        label: {
          normal: {
            show: true,
            position: 'right',
            fontSize: '10',
            formatter: (params) => `${formatNumber(params.value)}\n${params.data._percentageStr}`
          }
        },
      }
    ],
    color: BAR_COLOR_LIST[colorIndex]
  }
}

/**
 * 趋势表柱状表的series生成方法
 * @param name
 * @param data
 * @param color 当前柱子label的颜色，因为label颜色并不会继承柱子的颜色
 * @param seriesExtraParams (barWidth:柱子宽度，position: label位置)
 * @returns {{name: *, type: string, barWidth: number, data: *, label: {normal: {show: boolean, position: string, fontSize: string, color: *, formatter: (function(*): string)}}, itemStyle: null}}
 */
export function tendencyBarSeriesFactory(name, data, color, seriesExtraParams = {}) {
  const { barWidth = 16, position = 'top' } = seriesExtraParams
  return {
    name,
    type: 'bar',
    barWidth,
    data,
    label: {
      normal: {
        show: true,
        position,
        fontSize: '10',
        color,
        formatter: (params) => `${formatNumber(params.value)}\n${params.data._percentageStr}`
      }
    },
    //配置样式
    itemStyle: null,
  }
}

/**
 * 趋势表折线的series生成方法
 * @param name
 * @param data
 * @returns {{name: *, type: string, yAxisIndex: number, data: *, itemStyle: null}}
 */
export function tendencyLineSeriesFactory(name, data) {
  return {
    name,
    type: 'line',
    yAxisIndex: 1,
    data,
    //配置样式
    itemStyle: null,
  }
}

/**
 * 趋势表y轴生成方法
 * @param name
 * @param formatter
 * @param showLine  是否显示刻度线
 * @param axisLine 是否显示x轴线
 * @returns {*}
 */
export function tendencyYAxisFactory(name, formatter, showLine, axisLine = false) {
  return showLine ? {
    type: 'value',
    name,
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#EBF0F5'
      }
    },
    axisLine: {
      show: false
    },
    axisLabel: {
      formatter,
      color: '#B5C0CE',
      fontSize: 12
    },
    axisTick: {
      lineStyle: {
        color: '#EBF0F5'
      }
    }
  } : {
    type: 'value',
    name,
    splitLine: {
      show: false
    },
    axisLine: {
      show: axisLine
    },
    axisLabel: {
      formatter,
      color: '#B5C0CE',
      fontSize: 12
    },
    axisTick: {
      lineStyle: {
        color: '#EBF0F5'
      }
    }
  }
}

/**
 * 趋势表x轴生成方法
 * @param data
 * @returns {{type: string, data: *, axisPointer: {type: string}, axisLine: {lineStyle: {color: string}}, axisTick: {lineStyle: {color: string}}}}
 */
export function tendencyXAxisFactory(data) {
  return {
    type: 'category',
    data,
    axisPointer: {
      type: 'shadow'
    },
    axisLine: {
      lineStyle: {
        color: '#DBE6F3'
      }
    },
    axisTick: {
      lineStyle: {
        color: '#DBE6F3'
      }
    },
    axisLabel: {
      color: '#B5C0CE',
      fontSize: 12
    }
  }
}

/**
 * 趋势图模板生成方法
 * extraFormatter 除了params里面带的参数，如果还需要在tooltip显示的额外的信息，可放在extraFormatter中
 * hidePercent tooltip中是否显示每个系列的百分号
 * nameIsAbbreviation name值是否是经过_ts转化过的，如果是，为了使tooltip上能完全显示，需要另取值
 * @returns {{tooltip: {trigger: string, axisPointer: {type: string, crossStyle: {color: string}}, formatter: (function(*): string)}, legend: {data: Array, bottom: number, left: string}, xAxis: Array, yAxis: Array, series: Array, color: string[]}}
 */
export function tendencyTemplateFactory(extraFormatter = '', hidePercent = false, nameIsAbbreviation = false) {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      formatter: (params) => {
        let res, val, name;
        name = nameIsAbbreviation ? params[0].data.label : params[0].name
        res = extraFormatter ? `${extraFormatter}${name}<br/>` : `${name}<br/>`
        for (let i = 0, length = params.length; i < length; i++) {
          let { data = {}, value } = params[i];
          if (data._tooltipValue) {
            val = data._tooltipValue;
          } else {
            val = (value || value === 0) ? formatNumber(value) : "";
          }

          if (!hidePercent && data._percentageStr) {
            val += ` | ${data._percentageStr}`
          }

          res += params[i].seriesName + "：" + val + "<br/>";
        }
        return res;
      }
    },
    legend: {
      data: [],
      bottom: 10,
      left: 'center',
    },
    xAxis: [],
    yAxis: [],
    series: [],
    color: COLOR_LIST,
  }
}


/**
 * 设置饼状图柱子的颜色
 * @param indexActive 点击柱形图序号
 * @param itemLength 柱形图数量
 * @returns {Array}
 */
export function getBarOptionsColors(indexActive, itemLength) {
  let colorList = [];
  for (let i = 0; i < itemLength; i++) {
    colorList.push('#ddd')
  }
  colorList[indexActive] = '#00386b';
  return colorList;
}

/**
 * 获取当前被渲染的数据中，被激活项的index
 * @param params  被点击过的数据
 * @param options 当前画布被渲染的参数
 * @param compareKey  比较属性
 * @returns {number}
 */
export function getIndexActive(params, options, compareKey = 'criteria') {
  let criteria = params.data[compareKey];
  let indexActive = -1;
  options.series[0].data.find((item, index) => {
    if (typeof criteria === 'object') {
      return JSON.stringify(item[compareKey]) === JSON.stringify(criteria) && ((indexActive = index) || true);
    }
    return item[compareKey] === criteria && ((indexActive = index) || true);
  });
  return indexActive
}

/**
 * 点击时设置饼状图柱子的颜色
 * @param params  被点击过的数据
 * @param options 当前画布被渲染的参数
 * @param compareKey 比较属性
 * @returns {*|Array}
 */
export function getBarOptionsColorsByName(params, options, compareKey) {
  let itemLength = options.series[0].data.length;
  let indexActive = getIndexActive(params, options, compareKey);
  return getBarOptionsColors(indexActive, itemLength)
}

/**
 * 点击时设置柱形图柱子的颜色
 * @param params  被点击过的数据
 * @param options 当前画布被渲染的参数
 * @param compareKey 比较属性
 * @returns {{normal: {color: (function(*): *)}}}
 */
export function getActiveItemStyleByName(params, options, compareKey) {
  let itemLength = options.series[0].data.length;
  let indexActive = getIndexActive(params, options, compareKey);
  return {
    //通常情况下：
    normal: {
      //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
      color: function (params) {
        let colorList = [];
        for (let i = 0; i < itemLength; i++) {
          colorList.push('#ddd')
        }
        if (indexActive >= 0) {
          colorList[indexActive] = '#00386b';
        }
        return colorList[params.dataIndex];
      }
    },
  };
}


// 以下是周立的工具函数
/*
* 多字符换行
* 传入一个500个字符以下的字符串，转换为多行，因为在图表里面显示不全
* 每行40个
* */
export function lengthStrShow(str) {
  if (!str) return str;
  let regExp = /^(?!.*?[\u3000-\u303F\u4DC0-\u4DFF\u2800-\u28FF\u3200-\u32FF\u3300-\u33FF\u2700-\u27BF\u2600-\u26FF\uFE10-\uFE1F\uFE30-\uFE4F])[\u4e00-\u9fbb\u2E80-\uFE4F]+$/i;
  let resLine = [];
  if (str && str.length >= 40) {
    let singleLine = [];
    for (let i = 0, len = str.length; i < len; i++) {
      if (regExp.test(str[i])) {
        singleLine.push(str[i]);
        singleLine.push("");
      } else {
        singleLine.push(str[i]);
      }
      if (singleLine.length >= 40) {
        let cache = [...singleLine];
        resLine.push(cache.join(""));
        resLine.push('</br>');
        singleLine = [];
      }
    }
    resLine.push(singleLine.join(""));
    return resLine.join("");
  } else {
    return str
  }
}

/*
* 截取字符
* 字符串太长，截取前6个，其他以点显示
* */
export function _ts(str) {
  if (!str) return str;
  let regExp = /^(?!.*?[\u3000-\u303F\u4DC0-\u4DFF\u2800-\u28FF\u3200-\u32FF\u3300-\u33FF\u2700-\u27BF\u2600-\u26FF\uFE10-\uFE1F\uFE30-\uFE4F])[\u4e00-\u9fbb\u2E80-\uFE4F]+$/i;
  let res = '';
  let len = str.length;
  let sum = 0;
  for (let i = 0; i < len; i++) {
    let char = str[i];
    if (regExp.test(char)) {
      res += char;
      sum += 2;
    } else {
      res += char;
      sum += 1;
    }
    if (sum >= 10 && i < len) {
      res += '...';
      break;
    }
  }
  return res;
}
